package com.blb.demo1;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器端程序
 */
public class MyServer {

    public static final int PORT = 8888;

    public void start(){
        System.out.println("服务器启动了！");
        //创建ServerSocket对象      try(对象自动调用close)
        try (ServerSocket serverSocket = new ServerSocket(PORT)){
            while(true){
                //接收客户端连接Socket
                Socket client = serverSocket.accept();
                //获得客户端socket的输入流，用于读消息
                try(ObjectInputStream ois = new ObjectInputStream(client.getInputStream())) {
                    //读取文字
                    String msg = ois.readUTF();
                    System.out.println("客户端" + client.getInetAddress() + "说：" + msg);
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyServer myServer = new MyServer();
        myServer.start();
    }
}
